/**
 * Created by Tuffy on 16/6/6.
 */
'use strict';

adminCtrl

.controller('CompanyCtrl', ['$rootScope', '$scope', '$state', 'CompanyService', function ($rootScope, $scope, $state, CompanyService) {
	var id = $state.params.id;

    $scope.page = {
        pageNo: 1,
        totalPage: 0
    };

    $scope.companyData = {
    	id : null,
    	companyCode : null,
    	companyName : null,
    	provinceCode : null,
    	provinceName : null,
    	cityCode : null,
    	cityName : null,
    	updateTime : null,
    	createTime : null,
    	adminId : null,
        companyCategory: null
    };

    $scope.proDate = [];

    $scope.companyInfo = [];

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            loadData();
        }
    };

    // 初始化数据列表
    function loadData() {
    	CompanyService.list({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize
        }).success(function (result) {
            if (result.success) {
                $scope.companyInfo = result.data.companyInfo;
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }
    
    // 根据省编码 查询省下所有市
    $scope.selectCity = function () {
    	if ($scope.companyData.provinceCode) {
    		CompanyService.selectCity($scope.companyData.provinceCode)
    		.success(function (result) {
    			if(result.success){
    				$scope.cityDate = result.data.cityDate;
    			} else{
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
    			}
    		});
    	}
    };

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    }

    loadData();
}])

.controller('CompanyUserAddCtrl', ['$rootScope', '$scope', '$state', 'CompanyService', function($rootScope, $scope, $state, CompanyService) {
    // 注册对象
    $scope.signUserObj = {
        realName: null,
        name: null,
        phone: null,
        companyCode: null,
        email: null,
        companyCategory: null
    };

    $scope.categoryList = [{
        code: '30',
        name: '承运企业'
    }, {
        code: '40',
        name: '托运企业'
    }];

    $scope.company = [];
    // 加载公司下拉框
    $scope.loadCompany = function() {
        var index = layer.load(1, {
            shade: [0.1, '#fff']
        });
        CompanyService.selbycategory($scope.signUserObj.companyCategory)
            .success(function (result) {
                if (result.success) {
                    $scope.company = result.data
                } else {
                    layer.msg(result.message || '公司下拉框加载错误');
                }
            })
            .finally(function () {
                layer.close(index);
            });
    }


    $scope.loadDepartCity = function() {
        AreaService.loadCityByCode($scope.companyData.provinceCode)
            .success(function (result) {
                if (result.success) {
                    $scope.cityDate = result.data;
                }
            });
    };

    // 保存
    $scope.save = function() {
        var index = layer.load(1, {
            shade: [0.1, '#fff']
        });
        if (!Tools.account($scope.signUserObj.name)) {
            layer.msg('登录名称只能输入数字、字母、_');
            layer.close(index);
            return;
        }
        CompanyService.addCompanyUser($scope.signUserObj)
            .success(function(result) {
                if (result.success) {
                    //提示层
                    layer.msg('添加成功');
                    $state.go('company-user');
                } else {
                    layer.msg(result.message || '加载失败');
                }
            })
        .finally(function() {
            layer.close(index);
        });
    };

    // 加载公司下拉框数据
    // loadCompany();
}])

.controller('CompanyUserCtrl', ['$rootScope', '$scope', 'CompanyService', function ($rootScope, $scope, CompanyService) {
    $scope.page = {
        pageNo: 1,
        totalPage: 0
    };

    $scope.companyUserInfo = [];

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            loadData();
        }
    };

    // 初始化数据列表
    function loadData() {
        CompanyService.selectCompanyUser({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize
        }).success(function (result) {
            if (result.success) {
                $scope.companyUserInfo = result.data.companyUserInfo;
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    }

    loadData();
}])

.controller('CompanyEditCtrl', ['$rootScope', '$scope', '$state', 'AreaService', 'CompanyService', function($rootScope, $scope, $state, AreaService, CompanyService) {
	var id = $state.params.id;

    $scope.categoryList = [{
        code: 30,
        name: '承运企业'
    }, {
        code: 40,
        name: '托运企业'
    }];

    // 公司类型是否可编辑
    $scope.isShow = true;

    $scope.companyData = {
        id : null,
        companyCode : null,
        companyName : null,
        provinceCode : null,
        provinceName : null,
        cityCode : null,
        cityName : null,
        updateTime : null,
        createTime : null,
        adminId : null,
        companyCategory: null
    };

    // 加载省数据
    function loadProvince () {
        AreaService.loadProvince()
            .success(function (result) {
                if (result.success) {
                    $scope.proDate = result.data;
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
    }

    // 根据省编码查询发车市
    $scope.loadDepartCity = function() {
        AreaService.loadCityByCode($scope.companyData.provinceCode)
            .success(function (result) {
                if (result.success) {
                    $scope.cityDate = result.data;
                }
            });
    };

    // 保存公司信息
    $scope.saveCompany = function () {
    	delete $scope.companyData.updateTime;
    	delete $scope.companyData.createTime;
		CompanyService.saveCompany($scope.companyData)
		.success(function (result) {
			if(result.success){
				$state.go("company");
			} else{
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
			}
		})
    };

    // 根据公司编号  id 查询信息
    function companyView(id) {
    	if (id) {
    		CompanyService.companyView(id)
    		.success(function (result) {
    			if(result.success){
    				$scope.companyData = result.data.companyData;
                    $scope.loadDepartCity();
                    $scope.isShow = false;
    			} else{
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
    			}
    		})
    	}
    };

    loadProvince();
    companyView(id);
}])

.controller('CarInsuranceController', ['$rootScope', '$scope', 'CarInsuranceService', function ($rootScope, $scope, CarInsuranceService) {
    $scope.page = {
        pageNo: 1,
        totalPage: 0
    };
    
    $scope.orders = [];

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            loadData();
        }
    };

    // 初始化数据列表
    function loadData() {
    	CarInsuranceService.list({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize
        }).success(function (result) {
            if (result.success) {
                $scope.orders = result.data.orders;
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }
    
    // 导出
    $scope.exportCarInsurances = function () {
    	CarInsuranceService.exportCarInsurances()
		.success(function (result) {
			/*if(result.success){
				 $state.go("car-insurance-detail", {}, {reload: true});
			} else{
				alert(result.message);
			}*/
		})
    }

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    }

    loadData();
}])

.controller('CarTypeCtrl', ['$rootScope', '$scope', '$modal', 'CarTypeService', 'FuelService', function ($rootScope, $scope, $modal, CarTypeService, FuelService) {
    // 查询条件
    $scope.carType = {
        typeCode: '',
        typeName: '',
        licenseType: '',
        fuelTypeId: '',
        fuelConsumption: ''
    };

    $scope.carTypeInfo = {
        id: '',
        typeCode: '',
        typeName: '',
        licenseType: '',
        descripition: '',
        fuelTypeId: '',
        fuelConsumption: ''
    };

    // 数据列表
    $scope.carTypeList = [];

    // 默认保存
    $scope.saveOrUpdate = true;

    // 驾照类型
    $scope.licenseTypeList = [];

    // 燃油类型
    $scope.fuelTypeList = [];

    var carTypeModal = $modal({scope: $scope, title: '车辆类型', placement: 'center', templateUrl: $rootScope.Context.path + '/templates/ils/dialog/ils-car-type-modify-view.html', show: false});

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            $scope.loadData();
        }
    };

    // 初始化数据列表
    $scope.loadData = function (params) {
        if ('query' === params){
            $scope.userTruckObj.pageNo = 1;
            $scope.userTruckObj.pageSize = 10;
            $scope.page.pageNo = 1;
            $scope.page.totalPage = 0;
        }
        CarTypeService.pageList({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize,
            typeCode: $scope.carType.typeCode,
            typeName: $scope.carType.typeName,
            licenseType: $scope.carType.licenseType,
            fuelTypeId: $scope.carType.fuelTypeId,
            fuelConsumption: $scope.carType.fuelConsumption
        }).success(function (result) {
            if (result.success) {
                $scope.carTypeList = result.data.list;
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    // 清空查询条件
    $scope.clearQuery = function () {
        $scope.carType = {
            typeCode: '',
            typeName: '',
            licenseType: '',
            fuelTypeId: '',
            fuelConsumption: ''
        };
        $scope.loadData('query');
    };

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    };

    function cl() {
        $scope.carTypeInfo = {
            id: '',
            typeCode: '',
            typeName: '',
            licenseType: '',
            descripition: '',
            fuelTypeId: '',
            fuelConsumption: ''
        };
    }

    // 新增及修改
    $scope.saveCarType = function (saveOrUpdate) {
        if (saveOrUpdate) {
            if (validate()) {
                add();
            }
        } else {
            if (validate()) {
                update();
            }
        }
    };

    // 新增-dlg
    $scope.showAddDlg = function () {
        cl();
        $scope.saveOrUpdate = true;
        carTypeModal.$promise.then(carTypeModal.show);
    };

    // 新增
    function add() {
        CarTypeService.add($scope.carTypeInfo).success(function (result) {
            if (result.success) {
                $scope.loadData('load');
                carTypeModal.$promise.then(carTypeModal.hide);
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        })
    };

    // 修改
    function update() {
        delete $scope.carTypeInfo.createTime;
        delete $scope.carTypeInfo.updateTime;
        CarTypeService.update($scope.carTypeInfo).success(function (result) {
            if (result.success) {
                $scope.loadData('load');
                carTypeModal.$promise.then(carTypeModal.hide);
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        })
    };

    // 修改-dlg
    $scope.showUpdateDlg = function (item) {
        cl();
        CarTypeService.getById({id: item.id}).success(function(result) {
            if (result.success) {
                $scope.carTypeInfo = result.data;
                $scope.saveOrUpdate = false;
                carTypeModal.$promise.then(carTypeModal.show);
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        })
    };

    // 加载燃油类型
    function loadFuelType() {
        FuelService.list().success(function (result) {
            if (result.success) {
                $scope.fuelTypeList = result.data.list;
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        })
    }

    // 加载驾照类型
    function licenseTypeType() {
        CarTypeService.licenseTypeList().success(function (result) {
            if (result.success) {
                $scope.licenseTypeList = result.data;
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        })
    }

    // 校验
    function validate() {
        if (!$scope.saveOrUpdate) {
            if ($scope.carTypeInfo.id == '' || $scope.carTypeInfo.id == null) {
                $rootScope.hycadmin.toast({
                    title: '主键不能为空',
                    timeOut: 3000
                });
                return false;
            }
        }
        if ($scope.carTypeInfo.typeCode == '') {
            $rootScope.hycadmin.toast({
                title: '车型分类编号不能为空',
                timeOut: 3000
            });
            return false;
        } else if ($scope.carTypeInfo.typeName == '') {
            $rootScope.hycadmin.toast({
                title: '车型分类名称不能为空',
                timeOut: 3000
            });
            return false;
        } else if ($scope.carTypeInfo.licenseType == '') {
            $rootScope.hycadmin.toast({
                title: '准驾驾照类型不能为空',
                timeOut: 3000
            });
            return false;
        } else if ($scope.carTypeInfo.fuelTypeId == '') {
            $rootScope.hycadmin.toast({
                title: '燃油类型不能为空',
                timeOut: 3000
            });
            return false;
        } else if ($scope.carTypeInfo.fuelConsumption == '') {
            $rootScope.hycadmin.toast({
                title: '百公里油耗不能为空',
                timeOut: 3000
            });
            return false;
        } else if (!Tools.isNumberAndDoubleDigit($scope.carTypeInfo.fuelConsumption)) {
            $rootScope.hycadmin.toast({
                title: '百公里油耗只能为数字且为正数（保留两位小数）',
                timeOut: 3000
            });
            return false;
        }
        return true;
    }
    $scope.loadData('load');
    loadFuelType();
    licenseTypeType();
}])

.controller('CarOilChangeCtrl', ['$rootScope', '$scope', 'VehicleClassifyService', 'VehiclePkfeService', 'FuelPriceService', function ($rootScope, $scope, VehicleClassifyService, VehiclePkfeService, FuelPriceService) {
    // 查询条件
    $scope.carOil = {
        vehicleTypeId: '',
        fuelPriceId: '',
        effectiveDate: '',
        invalidDate: ''
    };

    // 数据列表
    $scope.carOilList = [];

    $scope.carList = [];

    $scope.fuelList = [];

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            $scope.loadData();
        }
    };

    // 初始化数据列表
    $scope.loadData = function (params) {
        if ('query' === params){
            $scope.userTruckObj.pageNo = 1;
            $scope.userTruckObj.pageSize = 10;
            $scope.page.pageNo = 1;
            $scope.page.totalPage = 0;
        }
        VehiclePkfeService.list({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize,
            vehicleTypeId: $scope.carOil.vehicleTypeId,
            fuelPriceId: $scope.carOil.fuelPriceId,
            effectiveDate: $scope.carOil.effectiveDate == ''?"": typeof ($scope.carOil.effectiveDate) == 'string'?$scope.carOil.effectiveDate : $scope.carOil.effectiveDate.format("yyyy-MM-dd 00:00:00")
        }).success(function (result) {
            if (result.success) {
                $scope.carOilList = result.data.list;
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };

    // 清空查询条件
    $scope.clearQuery = function () {
        $scope.carOil = {
            vehicleTypeId: '',
            fuelPriceId: '',
            effectiveDate: '',
            invalidDate: ''
        };
        $scope.loadData('query');
    };

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    };

    // 初始化车型
    function loadCarType () {
        VehicleClassifyService.list().success(function (result) {
            if (result.success) {
                $scope.carList = result.data;
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    // 初始化生效燃油
    function loadFuel () {
        FuelPriceService.list().success(function (result) {
            if (result.success) {
                $scope.fuelList = result.data;
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    loadCarType();
    loadFuel();
    $scope.loadData('load');
}])

.controller('CarRouteChangeCtrl', ['$rootScope', '$scope', '$modal', 'RouteFreightService', 'VehiclePkfeService', 'VehicleClassifyService', 'RouteService', function ($rootScope, $scope, $modal, RouteFreightService, VehiclePkfeService, VehicleClassifyService, RouteService) {
    // 查询条件
    $scope.routeVehicle = {
        routeId: '',
        vehicleTypeId: '',
        effectiveDate: ''
    };

    // 线路车型对象
    $scope.routeVehicleInfo = {
        id: '',
        routeId: '',
        vehicleTypeId: '',
        labourServicesPrice: '',
        totalPrice: '',
        effectiveDate: ''
    };

    // 数据列表
    $scope.routeVehicleList = [];

    // 线路列表
    $scope.routeList = [];

    // 车型列表
    $scope.carList = [];

    var carAddModal = $modal({scope: $scope, title: '车型线路价格', placement: 'center', templateUrl: $rootScope.Context.path + '/templates/ils/dialog/ils-car-route-add-view.html', show: false});

    var carUpdateModal = $modal({scope: $scope, title: '车型线路价格', placement: 'center', templateUrl: $rootScope.Context.path + '/templates/ils/dialog/ils-car-route-update-view.html', show: false});

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            $scope.loadData();
        }
    };

    // 初始化数据列表
    $scope.loadData = function (params) {
        if ('query' === params){
            $scope.userTruckObj.pageNo = 1;
            $scope.userTruckObj.pageSize = 10;
            $scope.page.pageNo = 1;
            $scope.page.totalPage = 0;
        }
        RouteVpeService.list({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize,
            routeId: $scope.routeVehicle.routeId,
            vehicleTypeId: $scope.routeVehicle.vehicleTypeId,
            effectiveDate: $scope.routeVehicle.effectiveDate == ''?"": typeof ($scope.routeVehicle.effectiveDate) == 'string'?$scope.routeVehicle.effectiveDate : $scope.routeVehicle.effectiveDate.format("yyyy-MM-dd 00:00:00")
        }).success(function (result) {
            if (result.success) {
                $scope.routeVehicleList = result.data.list;
                $scope.page = result.data.page;
                buildPage();
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };

    // 清空查询条件
    $scope.clearQuery = function () {
        $scope.routeVehicle = {
            routeId: '',
            vehicleTypeId: '',
            effectiveDate: ''
        };
        $scope.loadData('query');
    };

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    };

    // 初始化车型
    function loadCarType () {
        VehicleClassifyService.list().success(function (result) {
            if (result.success) {
                $scope.carList = result.data;
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    // 初始化线路
    function loadRoute () {
        RouteService.list().success(function (result) {
            if (result.success) {
                $scope.routeList = result.data.list;
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    function cl() {
        $scope.routeVehicleInfo = {
            id: '',
            routeId: '',
            vehicleTypeId: '',
            labourServicesPrice: '',
            totalPrice: '',
            effectiveDate: ''
        };
    }

    // 新增-dlg
    $scope.showAddDlg = function () {
        cl();
        carAddModal.$promise.then(carAddModal.show);
    };

    // 显示修改窗体
    $scope.showUpdateDlg = function(item) {
        cl();
        RouteVpeService.getById({
            id: item.id
        }).success(function (result) {
            if (result.success) {
                $scope.routeVehicleInfo = result.data;
                carUpdateModal.$promise.then(carUpdateModal.show);
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    };

    // 新增
    $scope.addCarRoute = function (isUpdate) {
        if (isUpdate) {
            if (validate(isUpdate)) {
                update();
            }
        } else {
            if (validate(isUpdate)) {
                add();
            }
        }

    };

    function add() {
        $scope.routeVehicleInfo.effectiveDate = $scope.routeVehicleInfo.effectiveDate == ''?"": typeof ($scope.routeVehicleInfo.effectiveDate) == 'string'?$scope.routeVehicleInfo.effectiveDate : $scope.routeVehicleInfo.effectiveDate.format("yyyy-MM-dd 00:00:00")
        RouteVpeService.add($scope.routeVehicleInfo).success(function (result) {
            if (result.success) {
                $scope.loadData('load');
                carAddModal.$promise.then(carAddModal.hide);
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    function update() {
        delete $scope.routeVehicleInfo.updateTime;
        delete $scope.routeVehicleInfo.createTime;
        $scope.routeVehicleInfo.effectiveDate = $scope.routeVehicleInfo.effectiveDate == ''?"": typeof ($scope.routeVehicleInfo.effectiveDate) == 'string'?$scope.routeVehicleInfo.effectiveDate : $scope.routeVehicleInfo.effectiveDate.format("yyyy-MM-dd 00:00:00")
        RouteVpeService.update($scope.routeVehicleInfo).success(function (result) {
            if (result.success) {
                $scope.loadData('load');
                carUpdateModal.$promise.then(carUpdateModal.hide);
            } else {
                $rootScope.hycadmin.toast({
                    title: result.message,
                    timeOut: 3000
                });
            }
        });
    }

    // 校验车型单公里价格是否存在
    $scope.existCarPk = function () {
        if ($scope.routeVehicleInfo.vehicleTypeId != '' && $scope.routeVehicleInfo.effectiveDate != '') {
            VehiclePkfeService.exist({
                vehicleTypeId: $scope.routeVehicleInfo.vehicleTypeId,
                effectiveDate: $scope.routeVehicleInfo.effectiveDate == ''?"": typeof ($scope.routeVehicleInfo.effectiveDate) == 'string'?$scope.routeVehicleInfo.effectiveDate : $scope.routeVehicleInfo.effectiveDate.format("yyyy-MM-dd 00:00:00")
            }).success(function (result) {
                if (result.success) {
                    if (!result.data) {
                        $rootScope.hycadmin.toast({
                            title: '不存当前车型生效的单公里油价',
                            timeOut: 3000
                        });
                    }
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
            if ($scope.routeVehicleInfo.labourServicesPrice != '') {
                $scope.reSetTotalCost();
            }
        }
    };

    // 重新计算总运费
    $scope.reSetTotalCost = function () {
        if (!Tools.isNumberAndDoubleDigit($scope.routeVehicleInfo.labourServicesPrice)) {
            $rootScope.hycadmin.toast({
                title: '劳务价只能为数字且为正数（保留两位小数）',
                timeOut: 3000
            });
            return false;
        }
        if ($scope.routeVehicleInfo.vehicleTypeId != '' && $scope.routeVehicleInfo.effectiveDate != '' && $scope.routeVehicleInfo.labourServicesPrice != '') {
            RouteVpeService.calctotal({
                vehicleTypeId: $scope.routeVehicleInfo.vehicleTypeId,
                labourServicesPrice: $scope.routeVehicleInfo.labourServicesPrice,
                effectiveDate: $scope.routeVehicleInfo.effectiveDate == ''?"": typeof ($scope.routeVehicleInfo.effectiveDate) == 'string'?$scope.routeVehicleInfo.effectiveDate : $scope.routeVehicleInfo.effectiveDate.format("yyyy-MM-dd 00:00:00")
            }).success(function(result){
                if (result.success) {
                    $scope.routeVehicleInfo.totalPrice = result.data;
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
        }
    };

    // 校验
    function validate(isUpdate) {
        if (isUpdate) {
            if ($scope.routeVehicleInfo.id == '') {
                $rootScope.hycadmin.toast({
                    title: '主键不能为空',
                    timeOut: 3000
                });
                return false;
            }
        }
        if ($scope.routeVehicleInfo.routeId == '') {
            $rootScope.hycadmin.toast({
                title: '线路不能为空',
                timeOut: 3000
            });
            return false;
        } else if ($scope.routeVehicleInfo.vehicleTypeId == '') {
            $rootScope.hycadmin.toast({
                title: '车型不能为空',
                timeOut: 3000
            });
            return false;
        } else if ($scope.routeVehicleInfo.labourServicesPrice == '') {
            $rootScope.hycadmin.toast({
                title: '劳务价不能为空',
                timeOut: 3000
            });
            return false;
        } else if (!Tools.isNumberAndDoubleDigit($scope.routeVehicleInfo.labourServicesPrice)) {
            $rootScope.hycadmin.toast({
                title: '劳务价只能为数字且为正数（保留两位小数）',
                timeOut: 3000
            });
            return false;
        } else if ($scope.routeVehicleInfo.effectiveDate == '') {
            $rootScope.hycadmin.toast({
                title: '生效时间不能为空',
                timeOut: 3000
            });
            return false;
        }
        return true;
    }

    loadCarType();
    loadRoute();
    $scope.loadData('load');
}])

    .controller('CarTypeFuelConsumptionImportCtrl', ['$rootScope', '$scope', '$modal', 'VehicleFuelImport', 'FileUploader', function ($rootScope, $scope, $modal, VehicleFuelImport, FileUploader) {

            var uploader = $scope.uploader = new FileUploader({
                url: '/upload/vehicleExcel',
                fileName : 'file'
            });
            // a sync filter
            uploader.filters.push({
                name: 'syncFilter',
                fn: function(item /*{File|FileLikeObject}*/, options) {
                    console.log('syncFilter');
                    return this.queue.length < 10;
                }
            });
            // CALLBACKS

            uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/, filter, options) {
                // console.info('onWhenAddingFileFailed', item, filter, options);
            };
            uploader.onAfterAddingFile = function(fileItem) {
                fileItem.upload();
                // console.info('onAfterAddingFile', fileItem);
            };
            uploader.onAfterAddingAll = function(addedFileItems) {
                // console.info('onAfterAddingAll', addedFileItems);
            };
            uploader.onBeforeUploadItem = function(item) {
                // console.info('onBeforeUploadItem', item);
            };
            uploader.onProgressItem = function(fileItem, progress) {
                // console.info('onProgressItem', fileItem, progress);
            };
            uploader.onProgressAll = function(progress) {
                // console.info('onProgressAll', progress);
            };
            uploader.onSuccessItem = function(fileItem, response, status, headers) {
                // console.info('onSuccessItem', fileItem, response, status, headers);
            };
            uploader.onErrorItem = function(fileItem, response, status, headers) {
                // console.info('onErrorItem', fileItem, response, status, headers);
            };
            uploader.onCancelItem = function(fileItem, response, status, headers) {
                // console.info('onCancelItem', fileItem, response, status, headers);
            };
            uploader.onCompleteItem = function(fileItem, response, status, headers) {

                // console.info('onCompleteItem', fileItem, response, status, headers);
                layer.msg(response.message);
                $scope.vehicleFuelInfo.batchId = response.data;
                $scope.loadExcelData(response.data);
            };
            uploader.onCompleteAll = function() {
                // console.info('onCompleteAll');
            };

            // console.info('uploader', uploader);

            $scope.vehicleFuelInfo = {
                id: '',
                vehicleClassId: '',
                vehicleClassName: '',
                tankVolume: '',
                oilTypeId: '',
                oilTypeName: '',
                standardOc: '',
                validateResultCode: '',
                validateResult: '',
                effectiveDate: '',
                batchId:''
            };

            function cl() {
                $scope.vehicleFuelInfo = {
                    id: '',
                    vehicleClassId: '',
                    vehicleClassName: '',
                    tankVolume: '',
                    oilTypeId: '',
                    oilTypeName: '',
                    standardOc: '',
                    effectiveDate: '',
                    batchId:''
                };
            }

            // 当前对象
            $scope.userTruckObj = {
                pageNo: 1,
                pageSize: 10,
                loadMore: function ($event, pageNo) {
                    this.pageNo = pageNo;
                    if ((this.pageNo > $scope.page.totalPage)) {
                        $event.stopPropagation();
                        this.pageNo = $scope.page.totalPage;
                        return;
                    } else if (this.pageNo < 1) {
                        $event.stopPropagation();
                        this.pageNo = 1;
                        return;
                    }
                    $scope.loadExcelData();
                }
            };

            //
            $scope.loadExcelData = function(data) {
                VehicleFuelImport.loadExcelData({
                    pageNo: $scope.userTruckObj.pageNo,
                    pageSize: $scope.userTruckObj.pageSize,
                    batchId:data
                }).success(function (result) {
                    if (result.success) {
                        $scope.vehicleList = result.data.list;
                        $scope.page = result.data.page;
                        buildPage();
                    }else {
                        layer.msg(result.message || '数据加载异常');
                    }
                });
            };

            function buildPage () {
                $scope.item = [];
                var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
                var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
                for(var i=start; i <= end; i++){
                    $scope.item.push(i);
                }
            };

            var vehicleFuelUpdateModal = $modal({scope: $scope, title: '车型油耗修改', placement: 'center', templateUrl: $rootScope.Context.path + '/templates/ils/dialog/ils-vehicle-fuel-update-view.html', show: false});

            // 显示修改窗体
            $scope.showUpdateDlg = function(item) {
                cl();
                VehicleFuelImport.getById({
                    id: item.id
                }).success(function (result) {
                    if (result.success) {
                        $scope.vehicleFuelInfo = result.data;
                        vehicleFuelUpdateModal.$promise.then(vehicleFuelUpdateModal.show);
                    } else {
                        layer.msg(result.message || '加载数据异常');
                    }
                });
            };

            $scope.update = function (){
                delete $scope.vehicleFuelInfo.updateTime;
                delete $scope.vehicleFuelInfo.createTime;
                $scope.vehicleFuelInfo.effectiveDate = $scope.vehicleFuelInfo.effectiveDate == ''?"": typeof ($scope.vehicleFuelInfo.effectiveDate) == 'string'?$scope.vehicleFuelInfo.effectiveDate : $scope.vehicleFuelInfo.effectiveDate.format("yyyy-MM-dd 00:00:00");
                VehicleFuelImport.update($scope.vehicleFuelInfo).success(function (result) {
                    if (result.success) {
                        $scope.loadExcelData($scope.vehicleFuelInfo.batchId);
                        vehicleFuelUpdateModal.$promise.then(vehicleFuelUpdateModal.hide);
                    } else {
                        layer.msg(result.message || '更新数据异常');
                    }
                });
            }


            $scope.del = function (item) {
                var index = layer.confirm('确定删除该数据？', {
                    btn: ['确定','取消'], //按钮,
                    skin: 'admin-confirm-btn-class',
                    title: '提示'
                }, function(){
                    layer.close(index);
                    if (item.id == '') {
                        layer.msg('删除标识不能为空');
                        return false;
                    }
                    VehicleFuelImport.del({id: item.id, batchId:$scope.vehicleFuelInfo.batchId}).success(function (result) {
                        if (result.success) {
                            $scope.loadExcelData($scope.vehicleFuelInfo.batchId);
                        } else {
                            layer.msg(result.message || '删除数据异常');
                        }
                    });
                });
            };

        $scope.delete = function () {
            var index = layer.confirm('确定取消导入？', {
                btn: ['确定', '取消'], //按钮,
                skin: 'admin-confirm-btn-class',
                title: '提示'
            }, function () {
                layer.close(index);
                window.location.reload();
                // VehicleFuelImport.delete().success(function (result) {
                //     if (result.success) {
                //         layer.msg(result.message || '取消导入成功');
                //         $scope.loadExcelData($scope.vehicleFuelInfo.batchId);
                //     } else {
                //         layer.msg(result.message || '取消导入异常');
                //     }
                // });
            });
        };


        $scope.importData = function (item) {
            var index = layer.confirm('确定导入？', {
                btn: ['确定', '取消'], //按钮,
                skin: 'admin-confirm-btn-class',
                title: '提示'
            }, function () {
                layer.close(index);
                if (item.validateResult != null) {
                    layer.msg('导入数据有错误不能导入！');
                    return false;
                }
                VehicleFuelImport.importData({batchId:$scope.vehicleFuelInfo.batchId}).success(function (result) {
                    if (result.success) {
                        $scope.loadExcelData($scope.vehicleFuelInfo.batchId);
                        layer.msg(result.message || '导入成功');
                    } else {
                        layer.msg(result.message || '导入数据异常');
                    }
                });
            });
            };
    }])
.controller('CvTankvolumeCtrl', ['$rootScope', '$scope', '$modal', 'CvTankvolumeService', 'VehicleClassifyService','VehicleService', function ($rootScope, $scope, $modal, CvTankvolumeService ,VehicleClassifyService,VehicleService) {
    // 查询条件
    $scope.scBaseCv = {
        cvTypeId:'',
        tankVolume:''

    };

    //
    $scope.scBaseCvInfo = {
        id:'',
        cvTypeId:'',
        cvBrandId:'',
        tankVolume:''
    };

    // 数据列表
    $scope.scBaseCvList = [];
    //商品车型
    $scope.carList = [];
    // 品牌数据
    $scope.brandList = [];

    var scBaseCvAddModal = $modal({scope: $scope, title: '车型油箱容积', placement: 'center', templateUrl: $rootScope.Context.path + '/templates/tankvolume/dialog/sc-base-cv-add-view.html', show: false});

    var scBaseCvUpdateModal = $modal({scope: $scope, title: '车型油箱容积', placement: 'center', templateUrl: $rootScope.Context.path + '/templates/tankvolume/dialog/sc-base-cv-update-view.html', show: false});

    // 当前对象
    $scope.userTruckObj = {
        pageNo: 1,
        pageSize: 10,
        loadMore: function ($event, pageNo) {
            this.pageNo = pageNo;
            if ((this.pageNo > $scope.page.totalPage)) {
                $event.stopPropagation();
                this.pageNo = $scope.page.totalPage;
                return;
            } else if (this.pageNo < 1) {
                $event.stopPropagation();
                this.pageNo = 1;
                return;
            }
            $scope.loadData();
        }
    };

    // 初始化数据列表
    $scope.loadData = function (params) {
        if ('query' === params){
            $scope.userTruckObj.pageNo = 1;
            $scope.userTruckObj.pageSize = 10;
            $scope.page.pageNo = 1;
            $scope.page.totalPage = 0;
        }
        CvTankvolumeService.pageList({
            pageNo: $scope.userTruckObj.pageNo,
            pageSize: $scope.userTruckObj.pageSize,
            cvTypeId:$scope.scBaseCv.cvTypeId,
            tankVolume:$scope.scBaseCv.tankVolume,

        }).success(function (result) {
            if (result.success) {
                $scope.scBaseCvList = result.data.list;
                $scope.page = result.data.page;
                buildPage();
            } else {
                layer.msg(result.message || '数据加载异常');
            }
        });
    };

    // 清空查询条件
    $scope.clearQuery = function () {
        $scope.scBaseCv = {
            cvTypeId:'',
            tankVolume:''
        };
        $scope.loadData('query');
    };

    function buildPage () {
        $scope.item = [];
        var end = ($scope.page.totalPage - $scope.userTruckObj.pageNo) > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)+5):(parseInt($scope.userTruckObj.pageNo)+5)):$scope.page.totalPage;
        var start = $scope.userTruckObj.pageNo > 5?($scope.userTruckObj.pageNo == 1?(parseInt($scope.userTruckObj.pageNo)-5):(parseInt($scope.userTruckObj.pageNo)-5)):1;
        for(var i=start; i <= end; i++){
            $scope.item.push(i);
        }
    };

    // 初始化车型
    function loadCarType () {
        VehicleClassifyService.list().success(function (result) {
            if (result.success) {
                $scope.carList = result.data;
            } else {
                layer.msg(result.message || '初始化车型下拉数据异常');
            }
        });
    }

    // 加载品牌
    $scope.loadBrand = function () {
        VehicleService.loadBrand()
            .success(function (result) {
                if (result.success) {
                    $scope.brandList = result.data;
                } else {
                    $rootScope.hycadmin.toast({
                        title: result.message,
                        timeOut: 3000
                    });
                }
            });
    };

    function cl() {
        $scope.scBaseCvInfo = {
            id:'',
            cvTypeId:'',
            cvBrandId:'',
            tankVolume:''
        };
    }

    // 新增-dlg
    $scope.showAddDlg = function () {
        cl();
        scBaseCvAddModal.$promise.then(scBaseCvAddModal.show);
    };

    // 显示修改窗体
    $scope.showUpdateDlg = function(item) {
        cl();
        CvTankvolumeService.getById({
            id: item.id
        }).success(function (result) {
            if (result.success) {
                $scope.scBaseCvInfo = result.data;
                scBaseCvUpdateModal.$promise.then(scBaseCvUpdateModal.show);
            } else {
                layer.msg(result.message || '加载数据异常');
            }
        });
    };

    // 新增
    $scope.addCarRoute = function (isUpdate) {
        if (isUpdate) {
            if (validate(isUpdate)) {
                update();
            }
        } else {
            if (validate(isUpdate)) {
                add();
            }
        }

    };

    function add() {
        CvTankvolumeService.add($scope.scBaseCvInfo).success(function (result) {
            if (result.success) {
                $scope.loadData('load');
                scBaseCvAddModal.$promise.then(scBaseCvAddModal.hide);
            } else {
                layer.msg(result.message || '添加数据异常');
            }
        });
    }

    $scope.del = function (item) {
        var index = layer.confirm('确定删除该数据？', {
            btn: ['确定','取消'], //按钮,
            skin: 'admin-confirm-btn-class',
            title: '提示'
        }, function(){
            layer.close(index);
            if (item.id == '') {
                layer.msg('删除标识不能为空');
                return false;
            }
            CvTankvolumeService.del({id: item.id}).success(function (result) {
                if (result.success) {
                    $scope.loadData('load');
                } else {
                    layer.msg(result.message || '删除数据异常');
                }
            });
        }, function(){
            //
        });
    };

    function update() {
        delete $scope.scBaseCvInfo.gmtCreate;
        delete $scope.scBaseCvInfo.gmtUpdate;
        CvTankvolumeService.update($scope.scBaseCvInfo).success(function (result) {
            if (result.success) {
                $scope.loadData('load');
                scBaseCvUpdateModal.$promise.then(scBaseCvUpdateModal.hide);
            } else {
                layer.msg(result.message || '更新数据异常');
            }
        });
    }

    // 校验
    function validate(isUpdate) {
        if (isUpdate) {
            if ($scope.scBaseCvInfo.id == '') {
                layer.msg('主键不能为空');
                return false;
            }
        }if($scope.scBaseCvInfo.cvTypeId==''){
            layer.msg('商品车类型不能为空');
            return false;
        }else if ($scope.scBaseCvInfo.cvBrandId == '') {
            layer.msg('商品车品牌不能为空');
            return false;
        }else if ($scope.scBaseCvInfo.tankVolume == '') {
            layer.msg('油箱容积不能为空');
            return false;
        } else if (!Tools.isNumberAndDoubleDigit($scope.scBaseCvInfo.tankVolume)) {
            layer.msg('油箱容积只能为数字且为正数（保留两位小数）');
            return false;
        }
        return true;
    }

    loadCarType();
    $scope.loadBrand();
    $scope.loadData('load');
}])
